package com.example.toy;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 多个ToySystem 构成的世界
 *
 * @author shenbing
 * @date 2021/12/23
 */
public class ToySystemCache {

  private static ToySystem defaultSystem = null;
  private static Map<String, ToySystem> systemWorld = new ConcurrentHashMap<>();

  public static synchronized void register(String name, ToySystem system, boolean asDefault) {
    if (systemWorld.containsKey(name)) {
      throw new IllegalArgumentException("ToySystemWorld already contains name: " + name);
    }
    systemWorld.put(name, system);
    if (asDefault || defaultSystem == null) {
      defaultSystem = system;
    }
  }

  public static synchronized void register(String name, ToySystem system) {
    register(name, system, false);
  }

  public static synchronized ToySystem getDefaultSystem() {
    return defaultSystem;
  }

  public static synchronized ToySystem getToySystem(String name) {
    return systemWorld.get(name);
  }

  public static synchronized boolean containsToySystem(String name) {
    return systemWorld.containsKey(name);
  }

  public static synchronized Map<String, ToySystem> getAllCachedToySystem() {
    return Collections.unmodifiableMap(systemWorld);
  }

  public static synchronized void unregister(String systemName) {
    ToySystem remove = systemWorld.remove(systemName);
    if (remove != null) {
      if (defaultSystem == remove) {
        defaultSystem = null;
      }
    }
  }
}
